<template>
  <div class="add-wrapper">
    <el-page-header @back="goBack" content="创建产品"> </el-page-header>
    <div class="form-wrapper">
      <div class="top-form">
        <div class="descLabel">基本信息</div>
        <!-- @keyup.enter.native="dataFormSubmitHandle()" -->
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          @submit.native.prevent
          label-width="120px"
        >
          <el-form-item v-if="!isAdd" prop="product_serial" label="产品编号">
            <el-input v-model="dataForm.product_serial" disabled></el-input>
          </el-form-item>
          <el-form-item prop="name" label="产品名称">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
          <el-form-item prop="classify_ids" label="产品分类">
            <el-cascader
              @change="treeChange"
              v-model="searchIds"
              :options="classifyList"
              :props="{ multiple: true, checkStrictly: true }"
              placeholder="产品分类"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item class="is-required" label="产品图片">
            <el-upload
              v-if="fileList.length <= 10"
              class="upload-demo"
              ref="upload"
              action=""
              :auto-upload="false"
              :file-list="fileList"
              :limit="10"
              :on-change="handleUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              list-type="picture-card"
              name="pic"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <div class="picDes">
              <div>上传说明：</div>
              <div>1.格式限制：JNG、PNG、JPEG</div>
              <div>2.大小限制：每张图片大小为10M以内，尺寸建议200*200</div>
              <div>
                3.最多可以上传10张图片，第一张将默认为主图，用于封面展示
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="sale_price" label="销售单价">
            <el-input
              type="number"
              v-model.number="dataForm.sale_price"
            ></el-input>
          </el-form-item>
          <el-form-item label="品牌" prop="brand">
            <el-input v-model="dataForm.brand"></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input
              placeholder="请输入"
              type="number"
              v-model.number="dataForm.sort"
            >
            </el-input>
            <div class="tipLabel">数值越大，排序越靠前</div>
          </el-form-item>
          <el-form-item label="产品有效期" prop="indate">
            <el-input
              placeholder="请输入"
              type="number"
              v-model.number="dataForm.indate"
              :disabled="useChecked"
            >
              <template slot="append">天</template>
            </el-input>
            <el-checkbox v-model="useChecked" @change="handleChange"
              >无</el-checkbox
            >
          </el-form-item>
          <el-form-item label="最小库存数" prop="min_stock">
            <el-input
              type="number"
              v-model.number="dataForm.min_stock"
            ></el-input>
            <div class="tipLabel">
              设置最小库存数后，若库存小于当前数值，系统将会报警提示用户
            </div>
          </el-form-item>
          <el-form-item label="报警天数" prop="alarm_day">
            <el-input
              placeholder="请输入"
              type="number"
              v-model.number="dataForm.alarm_day"
            >
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              placeholder="请输入"
              type="textarea"
              :rows="3"
              v-model="dataForm.remarks"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="size-form padTop20">
        <div class="descLabel">产品规格</div>
        <el-form @submit.native.prevent label-width="120px">
          <el-form-item label="规格" v-if="isAdd">
            <div class="specWrapper">
              <div
                class="specBox"
                v-for="(item, index) in sizeList"
                :key="index"
              >
                <div class="disCenterBetween">
                  <div class="verticalCenter">
                    <div class="specLabel">规格名称</div>
                    <el-input
                      placeholder="请输入"
                      v-model="item.spec_title"
                      @change="handleGenerateSize($event, 'parent', index)"
                    >
                    </el-input>
                  </div>
                  <el-button
                    type="text"
                    @click="handleRemoveSizeItem(index)"
                    :disabled="sizeList.length < 2"
                    ><i
                      class="el-icon-close"
                      style="font-size: 24px; margin-left: 16px"
                    ></i
                  ></el-button>
                  <!-- <el-button
                    type="primary"
                    style="margin-left: 16px"
                    @click="handleRemoveSizeItem(index)"
                    >删除</el-button
                  > -->
                </div>
                <div>
                  <div class="specContent verticalCenter">
                    <div class="contentLabel">选项名称</div>
                    <span
                      class="contentInputItem"
                      v-for="(it, idx) in item.spec_item"
                      :key="idx"
                    >
                      <!-- @blur="handleBlur" -->
                      <el-input
                        placeholder="请输入"
                        v-model="it.name"
                        @focus="handleFocus(index, idx)"
                        @change="handleGenerateSize($event, 'sub', index, idx)"
                      >
                      </el-input>
                      <el-button
                        type="text"
                        @click="handleRemoveItem(index, idx)"
                        v-if="item.spec_item.length > 1 && it.closeShow"
                        ><i class="el-icon-close itemClose"></i
                      ></el-button>
                    </span>
                    <!-- <el-button
                      type="text"
                      @click="handleRemoveItem(index)"
                      :disabled="item.spec_item.length < 2"
                      ><i
                        class="el-icon-remove-outline"
                        style="font-size: 24px; margin-left: 16px"
                      ></i
                    ></el-button> -->
                    <el-button
                      type="text"
                      v-show="item.spec_item.length < 5"
                      :disabled="getStatus(index)"
                      @click="handleAddSizeItem(index)"
                      ><i
                        class="el-icon-circle-plus-outline"
                        style="font-size: 24px; margin-left: 16px"
                      ></i
                    ></el-button>
                  </div>
                </div>
              </div>
              <div style="margin-top: 20px">
                <el-button
                  type="primary"
                  @click="handleAddSize"
                  v-show="sizeList.length < 2"
                  >添加规格</el-button
                >
                <!-- <el-button
                  type="primary"
                  @click="handleGenerateSize"
                  :style="`margin-left: ${sizeList.length > 1 ? '0' : '16px'}`"
                  >生成规格表</el-button
                > -->
              </div>
            </div>
          </el-form-item>
          <el-form-item label="">
            <!-- <el-button type="primary" @click="batchAdd">计算</el-button> -->
            <div style="display: flex">
              <div>
                <span>批量销售单价</span>
                <el-input
                  placeholder="请输入"
                  type="number"
                  v-model="batchPrice"
                  @input="(e) => handleInput(e, 'batchPrice')"
                >
                </el-input>
              </div>
              <div style="margin-left: 16px">
                <span>批量产品有效期</span>
                <el-input
                  placeholder="请输入"
                  type="number"
                  v-model="batchExpire"
                  @input="(e) => handleInput(e, 'batchExpire')"
                >
                </el-input>
              </div>
              <div style="margin-left: 16px">
                <span>批量最小库存</span>
                <el-input
                  placeholder="请输入"
                  type="number"
                  v-model="batchLimit"
                  @input="(e) => handleInput(e, 'batchLimit')"
                >
                </el-input>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="规格表">
            <!-- :span-method="objectSpanMethod" -->
            <!-- :span-method="objectSpanMethod" -->
            <el-table
              class="tableWrapper"
              :data="generateList"
              border
              style="width: 100%; margin-top: 20px"
            >
              <el-table-column
                v-for="(item, index) in headerTitleList"
                :key="index"
                :prop="`title_${index}`"
                :label="item.spec_title"
                width="180"
                header-align="center"
                align="center"
              >
              </el-table-column>
              <el-table-column
                prop="pic"
                label="SKU图片"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <el-upload
                    class="upload-demo"
                    ref="upload"
                    action=""
                    :auto-upload="false"
                    :file-list="scope.row.pics"
                    :limit="1"
                    :on-change="(file) => handleTableUpload(file, scope)"
                    :on-remove="(file) => handleTableRemove(file, scope)"
                    list-type="picture-card"
                    name="pic"
                    :class="{ hide: scope.row.pics.length > 0 }"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column
                prop="sale_price"
                label-class-name="thRequired"
                label="销售单价（人民币）"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <!-- v-model.number="scope.row.num" -->
                  <el-input
                    type="number"
                    placeholder="请输入"
                    v-model.number="scope.row.sale_price"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="indate"
                label="产品有效期"
                header-align="center"
                align="center"
              >
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入"
                    type="number"
                    v-model.number="scope.row.indate"
                  >
                    <template slot="append">天</template>
                  </el-input>
                </template>

                <!-- <el-checkbox v-model="useChecked" @change="handleChange"
              >无</el-checkbox
            > -->
              </el-table-column>
              <el-table-column
                prop="min_stock"
                label="库存限制"
                header-align="center"
                align="center"
                min-width="120"
              >
                <template slot-scope="scope">
                  <div class="disCenterBetween">
                    <span style="width: 80px; margin-right: 16px"
                      >最小库存</span
                    >
                    <el-input
                      placeholder="请输入"
                      type="number"
                      v-model.number="scope.row.min_stock"
                    >
                    </el-input>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>

      <div class="pack-form padTop20">
        <div class="descLabel">包装信息</div>
        <!-- @keyup.enter.native="dataFormSubmitHandle()" -->
        <el-form
          :model="packForm"
          ref="packForm"
          @submit.native.prevent
          label-width="120px"
        >
          <el-form-item label="包装要求" prop="packaging">
            <el-input v-model="packForm.packaging"></el-input>
          </el-form-item>
          <el-form-item label="每箱个数" prop="box_capacity">
            <el-input
              placeholder="请输入"
              type="number"
              v-model.number="packForm.box_capacity"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="纸箱尺寸" prop="box_size_long">
            <div class="verticalCenter">
              <div class="disCenterBetween">
                长
                <el-input
                  placeholder="请输入"
                  type="number"
                  v-model.number="packForm.box_size_long"
                  style="margin: 0 8px; width: 120px"
                >
                </el-input>
                cm
              </div>
              <div style="margin: 0 12px">*</div>
              <div class="disCenterBetween">
                宽
                <el-input
                  placeholder="请输入"
                  type="number"
                  v-model.number="packForm.box_size_wide"
                  style="margin: 0 8px; width: 120px"
                >
                </el-input>
                cm
              </div>
              <div style="margin: 0 12px">*</div>
              <div class="disCenterBetween">
                高
                <el-input
                  placeholder="请输入"
                  type="number"
                  v-model.number="packForm.box_size_high"
                  style="margin: 0 8px; width: 120px"
                >
                </el-input>
                cm
              </div>
            </div>
          </el-form-item>
          <el-form-item label="其他特殊要求" prop="others_remarks">
            <el-input
              placeholder="请输入"
              type="textarea"
              :rows="3"
              v-model="packForm.others_remarks"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div style="margin-bottom: 36px">
      <el-button @click="goBack" style="margin-left: 45%; margin-top: 36px"
        >取消</el-button
      >
      <el-button
        type="primary"
        @click="dataFormSubmitHandle()"
        style="margin-left: 21px"
        >确定</el-button
      >
    </div>
    <el-backtop></el-backtop>
    <el-dialog :visible.sync="dialogVisible" title="查看">
      <img width="100%" :src="dialogImageUrl" class="avatar" />
    </el-dialog>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import cloneDeep from 'lodash/cloneDeep'
import { isEmail, isMobile } from '@/utils/validate'
import { jsonObjToFormObj, transCascader } from '@/utils'
import {
  selfUpload,
  getProductClassify,
  addProduct,
  editProduct,
  getProductDetail,
} from '@/api'
export default {
  data() {
    return {
      dataForm: {
        id: '',
        name: '',
        classify_ids: [],
        product_serial: '',
        sale_price: null,
        brand: '',
        sort: null,
        indate: null,
        min_stock: null,
        alarm_day: null,
        remarks: '',
      },
      packForm: {
        packaging: '',
        box_capacity: null,
        box_size_long: null,
        box_size_wide: null,
        box_size_high: null,
        others_remarks: '',
      },
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      useChecked: false,
      // 规格列表
      sizeList: [
        {
          spec_title: '',
          spec_item: [{ name: '' }],
        },
        // {
        //   spec_title: "颜色",
        //   spec_item: [{ name: "红" }, { name: "黑" }],
        // },
        // {
        //   spec_title: "尺寸",
        //   spec_item: [{ name: "S" }, { name: "M" }, { name: "L" }],
        // },
      ],
      generateList: [],
      headerTitleList: [],
      batchPrice: 0,
      batchExpire: 0,
      batchLimit: 0,
      isAdd: true,
      value: '',
      classifyList: [],
      searchIds: [],
    }
  },
  computed: {
    dataRule() {
      return {
        name: [
          {
            required: true,
            message: '必填项不能为空',
            trigger: 'blur',
          },
        ],
        classify_ids: [
          {
            required: true,
            message: '必选项不能为空',
            trigger: 'change',
          },
        ],
        sale_price: [
          {
            required: true,
            message: '必填项不能为空',
            trigger: 'blur',
          },
        ],
      }
    },
  },
  activated() {
    let that = this
    this.$nextTick(() => {
      that.$refs['dataForm'].resetFields()
      that.$refs['packForm'].resetFields()
      this.packForm.box_size_wide = null
      this.packForm.box_size_high = null
      that.fileList = []
      that.sizeList = [
        {
          spec_title: '',
          spec_item: [{ name: '', closeShow: false }],
        },
      ]
      that.generateList = []
      that.headerTitleList = []
      that.batchPrice = 0
      that.batchExpire = 0
      that.batchLimit = 0
      that.searchIds = []
      const id = that.$route.params.id
      that.dataForm.id = id
      that.fetchClassifytList()
      if (id) {
        that.fetchDetail(id)
        that.isAdd = false
      }
    })
  },
  methods: {
    async handleTableUpload(file, scope) {
      let index = scope.$index
      // const isLt10M = file.size / 1024 / 1024 < 10
      // if (!isLt10M) {
      //   this.$message.error('上传图片大小不能超过 10MB!')
      //   this.$refs.upload.clearFiles()
      //   return
      // }
      const params = {}
      params.file = file.raw
      const formData = jsonObjToFormObj(params)
      const res = await selfUpload(formData)
      if (res?.status === 1) {
        this.$message({
          message: res.msg,
          type: 'success',
          duration: '1000',
        })
        this.hideUpload = true
        const arr = [
          {
            url: res?.url || '',
            uid: file.uid,
          },
        ]
        this.generateList[index].pics = arr
        // this.fileList.push();
      }
    },
    handleTableRemove(file, scope) {
      let index = scope.$index
      let pics = this.generateList[index].pics
      pics.map((item, index) => {
        if (item.uid == file.uid) {
          pics.splice(index, 1)
        }
      })
    },
    handleBlur() {
      this.sizeList.forEach((item) => {
        item.spec_item.forEach((it) => {
          it.closeShow = false
        })
      })
      this.$forceUpdate()
    },
    handleFocus(index, idx) {
      const item = this.sizeList[index].spec_item
      const filterItems = item.filter((it, idF) => idF !== idx)
      filterItems.forEach((iS) => (iS.closeShow = false))
      item[idx].closeShow = true
      this.$forceUpdate()
    },
    getStatus(index) {
      const item = this.sizeList[index]
      const temp = item.spec_item.filter((it) => it.name === '')
      if (temp.length > 0) {
        return true
      }
      return false
    },
    treeChange() {
      let arr = []
      this.searchIds.forEach((item) => {
        arr.push(item[item.length - 1])
      })
      this.dataForm.classify_ids = arr
    },
    async fetchDetail(id) {
      const params = {
        id,
      }
      const res = await getProductDetail(params)
      if (res?.status === 1) {
        const data = res?.data || {}
        const {
          sku_list,
          packaging,
          box_capacity,
          box_size_long,
          box_size_wide,
          box_size_high,
          others_remarks,
          ...info
        } = data
        this.dataForm = info
        this.packForm = {
          packaging,
          box_capacity,
          box_size_long,
          box_size_wide,
          box_size_high,
          others_remarks,
        }
        // const ids = classify_ids.split(',')
        // this.dataForm.classify_ids = ids
        let temp = []
        let ids = data.classify_ids
        for (let i = 0; i < ids.length; i++) {
          let data = transCascader(ids[i], this.classifyList)
          temp.push(data)
        }
        this.searchIds = temp
        console.log(temp)
        // debugger
        // this.value = info
        if (data.is_spec === 1) {
          sku_list.forEach((item, index) => {
            const temp = item.sku_name.split('+')
            item.title_0 = temp[0]
            item.title_1 = temp[1]
            item.spec_title = `规格${index + 1}`
          })
          this.headerTitleList = [
            { spec_title: '规格1' },
            { spec_title: '规格2' },
          ]
        } else {
          sku_list.forEach((item) => {
            item.title_0 = item.sku_name
            item.spec_title = `规格${index + 1}`
          })
          this.headerTitleList = [{ spec_title: '规格1' }]
        }
        this.generateList = sku_list
        console.log(this.generateList)
        const pics = data?.pics
        if (pics.length > 0) {
          const arr = []
          pics.forEach((item) => {
            arr.push({ name: '', url: item || '' })
          })
          this.fileList = arr
        }
      }
    },
    // 获取tree
    async fetchClassifytList() {
      const res = await getProductClassify()
      if (res?.status === 1) {
        this.classifyList = res.list
        console.log(this.classifyList)
      }
    },
    handleInput(e, type) {
      if (this.generateList.length < 1) {
        this.$message.warning('请生成规格表后再设置批量数据！')
        return
      }
      this[type] = e
      const key =
        type === 'batchPrice'
          ? 'sale_price'
          : type === 'batchExpire'
          ? 'indate'
          : 'min_stock'
      this.generateList.forEach((item) => (item[key] = e))
      // this.$confirm('此操作将批量修改数据, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // })
      //   .then(() => {})
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消更改',
      //     })
      //   })
    },
    batchAdd() {
      console.log(this.generateList)
      console.log(this.sizeList)
    },
    handleGenerateSize(e, from, index, idx) {
      // console.log(e)
      // console.log(from)
      console.log(this.sizeList)
      let tempSize = []
      if (e) {
        if (from === 'parent') {
          this.sizeList.forEach((item) => tempSize.push(item.spec_title))
        } else {
          this.sizeList[index].spec_item.forEach((item) =>
            tempSize.push(item.name)
          )
        }

        console.log(tempSize)
        let count = 0
        tempSize.forEach((item) => {
          if (item === e) count++
        })
        console.log(count)
        if (count > 1) {
          let tip =
            from === 'parent'
              ? '规格名称重复，请重新填写'
              : '选项名称重复，请重新填写'
          this.$message.warning(tip)
          if (from === 'parent') {
            this.sizeList.splice(index, 1)
            // this.sizeList[index].spec_title = ''
            // this.sizeList[index].spec_item = []
          } else {
            // this.sizeList[index].spec_item[idx].name = ''
            this.sizeList[index].spec_item.splice(idx, 1)
          }

          // return
        }
      }
      console.log(this.sizeList)
      // debugger
      this.headerTitleList = cloneDeep(this.sizeList)
      let temp = []
      let arr1 = []
      let arr2 = []
      if (this.sizeList.length > 1) {
        arr1 = this.sizeList[0].spec_item.filter((item) => item.name !== '')
        arr2 = this.sizeList[1].spec_item.filter((item) => item.name !== '')
        for (let j = 0; j < arr1.length; j++) {
          for (let k = 0; k < arr2.length; k++) {
            const key = 'title_0'
            const sub = 'title_1'
            temp.push({
              [key]: arr1[j].name,
              [sub]: arr2[k].name,
              sale_price: null,
              indate: null,
              min_stock: null,
              pics: [],
            })
          }
        }
      } else {
        let item = this.sizeList[0].spec_item.filter((item) => item.name !== '')
        item.forEach((item) =>
          temp.push({
            title_0: item.name,
            sale_price: null,
            indate: null,
            min_stock: null,
            pics: [],
          })
        )
      }
      this.generateList = temp
    },
    handleRemoveSizeItem(index) {
      if (this.sizeList.length < 2) {
        this.$message.warning('无法删除，请至少保留一项数据！')
        return
      }
      this.sizeList.splice(index, 1)
      this.handleGenerateSize()
    },
    handleRemoveItem(index, idx) {
      const item = this.sizeList[index].spec_item
      if (item.length < 2) {
        this.$message.warning('请至少保留一项！')
        return
      }
      this.sizeList[index].spec_item.splice(idx, 1)
      this.handleGenerateSize()
    },
    handleAddSizeItem(index) {
      // console.log(this.sizeList)
      const item = this.sizeList[index].spec_item
      if (item.length >= 5) {
        this.$message.warning('选项至多添加5个!')
        return
      }
      this.sizeList[index].spec_item.push({
        name: '',
        closeShow: false,
      })
    },
    handleAddSize() {
      console.log(this.sizeList)
      if (this.sizeList.length >= 2) {
        this.$message.warning('规格至多添加2个!')
        return
      }
      this.sizeList.push({
        spec_title: '',
        spec_item: [{ name: '', closeShow: false }],
      })
      this.$forceUpdate()
    },
    handleChange(val) {
      this.useChecked = val
      if (val) this.dataForm.indate = null
    },
    async handleUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        this.$refs.upload.clearFiles()
        return
      }
      const params = {}
      params.file = file.raw
      const formData = jsonObjToFormObj(params)
      const res = await selfUpload(formData)
      if (res?.status === 1) {
        this.$message({
          message: res.msg,
          type: 'success',
          duration: '1000',
        })
        this.fileList.push({
          url: res?.url || '',
          uid: file.uid,
        })
      }
    },
    goBack() {
      this.$refs['dataForm'].resetFields()
      this.$refs['packForm'].resetFields()
      this.$router.go(-1)
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let len
      if (this.sizeList.length > 1) {
        len = this.sizeList[1].spec_item.length
      } else {
        len = 1
      }
      if (columnIndex === 0) {
        if (rowIndex % len === 0) {
          return {
            rowspan: len,
            colspan: 1,
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          }
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file) {
      console.log(this.fileList)
      this.fileList.map((item, index) => {
        if (item.uid == file.uid) {
          this.fileList.splice(index, 1)
        }
      })
    },

    // 表单提交
    dataFormSubmitHandle: debounce(
      function() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (!valid) {
            return false
          }
          const params = { ...this.dataForm, ...this.packForm }
          params.id = this.dataForm.id ? this.dataForm.id : 0

          // 产品图片
          const arr = []
          if (this.fileList.length > 0) {
            this.fileList.forEach((item) => arr.push(item.url))
          }
          params.pics = arr
          if (this.generateList.length < 1) {
            this.$message.warning('请至少输入一个产品规格!')
            return
          }
          // 规格项处理
          const opts = {}
          for (let i = 0; i < this.generateList.length; i++) {
            let item = this.generateList[i]
            let key = `${item.title_0}`
            if (item.title_1) key += `+${item.title_1}`
            let innerObj = {}
            innerObj.sale_price = item.sale_price
            innerObj.indate = item.indate
            innerObj.min_stock = item.min_stock
            let pic = ''
            if (item.pics.length > 0) pic = item.pics[0].url
            innerObj.pic = pic
            innerObj.min_stock = item.min_stock
            opts[key] = innerObj
          }
          params.options = opts
          const temp = []
          // spec_list规格数据处理
          for (let i = 0; i < this.sizeList.length; i++) {
            let list = this.sizeList
            let obj = {}
            obj.spec_title = list[i].spec_title
            obj.spec_item = []
            for (let j = 0; j < list[i].spec_item.length; j++) {
              obj.spec_item.push(list[i].spec_item[j].name)
            }
            temp.push(obj)
          }
          params.spec_list = temp
          // debugger;
          // return;
          let methodName = addProduct
          if (!this.isAdd) methodName = editProduct
          const res = await methodName(params)
          if (res?.status === 1) {
            this.$message.success(res?.msg || '操作成功')
            this.$refs['dataForm'].resetFields()
            this.$refs['packForm'].resetFields()
            this.$refs.upload.clearFiles()
            this.fileList = []
            this.$router.go(-1)
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
}
</script>

<style lang="scss" scoped>
.add-wrapper {
  background: #fff;
  padding: 20px;
  ::v-deep .el-page-header__title {
    font-size: 12px;
  }

  ::v-deep .el-page-header__content {
    font-size: 12px;
  }

  .form-wrapper {
    ::v-deep .el-select {
      width: 100%;
    }

    .top-form {
      width: 50%;
      margin-top: 36px;

      .picDes {
        margin-top: 12px;
        font-size: 12px;
        color: #999;
        line-height: 18px;
      }
    }

    .pack-form {
      width: 50%;
    }

    .size-form {
      .specWrapper {
        padding: 20px;
        background: #f5f5f5;
        .specBox {
          margin-top: 28px;
          &:first-child {
            margin-top: 0;
          }
          .specLabel {
            color: $mainColor;
            margin-right: 16px;
          }
          .specContent {
            margin-top: 20px;
            .contentLabel {
              margin-right: 16px;
            }
            .contentInputItem {
              margin-left: 12px;
              position: relative;
              &:nth-child(2) {
                margin-left: 0;
              }
              .itemClose {
                font-size: 16px;
                font-weight: 600;
                position: absolute;
                right: 0;
                top: -18px;
                color: $mainColor;
                cursor: pointer;
              }
            }
          }
          .el-input {
            width: 10vw;
          }
        }
      }

      .tableWrapper {
        ::v-deep .el-upload--picture-card {
          width: 64px;
          height: 64px;
          line-height: 80px;
        }

        ::v-deep .el-upload-list--picture-card .el-upload-list__item {
          width: 64px;
          height: 64px;
          margin: 0;
        }
      }
    }
  }
  .hide {
    ::v-deep .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
